<form class="area" method="post" style="padding-bottom:40px;">
    <dl class="optBox mt20">
        <dt class="opt"><label class="lb" for="">管理员头像</label></dt>
        <dd class="opCon">
            <div id="uploader-demo">
                <!--用来存放item-->
                <input type="hidden" id="img"  value="{{adminUser['img']}}" />
                <div id="fileList" class="uploader-list">
                    {% if adminUser['img'] %}
                    <div id="' + file.id + '" class="file-item thumbnail">
                        <img src="{{adminUser['img']}}" style="height: 300px;width: 400px" >
                        <div class="info">{{ad['img']}}</div>
                    </div>
                    {% endif %}
                </div>
                <div id="filePicker">选择图片</div>
            </div>
        </dd>
    </dl>
    <dl class="optBox mt20">
        <dt class="opt"><label class="lb" for="">用户名</label></dt>
        <dd class="opCon">
            {{adminUser['username']}}
            <p class="tip"></p>
        </dd>
    </dl>
    <dl class="optBox mt20">
        <dt class="opt"><label class="lb" for="">管理角色</label></dt>
        <dd class="opCon">
            {% for remark in remarks %}
            {% if remark['id'] == adminUser['roleId'] %}
                {{ remark['remark'] }}
            {% endif %}
            {% endfor %}
            <p class="tip"></p>
        </dd>
    </dl>
    <dl class="optBox mt20">
        <dt class="opt"><label class="lb" for="">密码</label></dt>
        <dd class="opCon">
            <input type="password" name="password" id="password" class="txt">
            <p class="tip"></p>
        </dd>
    </dl>
    <dl class="optBox mt20">
        <dt class="opt"><label class="lb" for="">新密码</label></dt>
        <dd class="opCon">
            <input type="password" name="newPassword" id="newPassword" class="txt">
            <p class="tip"></p>
        </dd>
    </dl>

    <p class="mt20 tc"><input type="button" style="width: 100px; height:30px;" value="修改"   id="btnsubmit"  /><input type="button" style="width: 100px; height:30px;"  value="返回"  class="btn-back"  /></p>
</form>

<input type="hidden" value="{{url("usermanage/updateUser")}}" id="clicksaveRole">


<link rel="stylesheet" type="text/css" href="{{constant('MANAGE_JS_PATH')}}webuploader-0.1.5/webuploader.css">

<script type="text/javascript" src="{{constant('MANAGE_JS_PATH')}}webuploader-0.1.5/webuploader.nolog.js"></script>

<script type="text/javascript">

    var dir = "";
    var service = "";
    var fileName = "";
    // 初始化Web Uploader
    var uploader = WebUploader.create({
        // 选完文件后，是否自动上传。
        auto: true,
        // swf文件路径
        swf: "{{constant('MANAGE_JS_PATH')}}webuploader-0.1.5/Uploader.swf",
        // 文件接收服务端。
//    server: 'http://testimg-xuzhong.oss-cn-shanghai.aliyuncs.com',
        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: '#filePicker',
        // 只允许选择图片文件。
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/jpg,image/jpeg,image/png'
        }

    });


    // 当有文件添加进来的时候
    uploader.on('fileQueued', function (file) {
        $.ajax({
            url: "{{constant('APP_URL')}}" + '/Web/getOssSign/type/1',
            type: 'get',
            async: false, //使用同步的方式,true为异步方式
            success: function (res) {
                res = res.data;
                dir = res.dir;
                service = res.host;
                uploader.option('formData', {
                    "success_action_status": 200,
                    "OSSAccessKeyId": res.accessid,
                    "policy": res.policy,
                    "signature": res.signature
                });
                uploader.option("server", res.host)
//            console.log(uploader)
                //code here...
            },
            dataType: 'json'
        });
        fileName = calculate_object_name(file.name);
        uploader.option('formData', {
            "key": dir + fileName,
        });
        var $li = $(
                '<div id="' + file.id + '" class="file-item thumbnail">' +
                '<img>' +
                '<div class="info">' + service + "/" + dir + fileName + '</div>' +
                '</div>'
            ),
            $img = $li.find('img');
        // $list为容器jQuery实例
        $("#fileList").html($li);
        $("#img").val(service + "/" + dir + fileName);
        // 创建缩略图
        // 如果为非图片文件，可以不用调用此方法。
        // thumbnailWidth x thumbnailHeight 为 100 x 100
        var thumbnailWidth = 400;
        var thumbnailHeight = 300;
        uploader.makeThumb(file, function (error, src) {
            if (error) {
                $img.replaceWith('<span>不能预览</span>');
                return;
            }

            $img.attr('src', src);
        }, thumbnailWidth, thumbnailHeight);
    });
    // 文件上传过程中创建进度条实时显示。
    uploader.on('uploadProgress', function (file, percentage) {
        var $li = $('#' + file.id),
            $percent = $li.find('.progress span');
        // 避免重复创建
        if (!$percent.length) {
            $percent = $('<p class="progress"><span></span></p>')
                .appendTo($li)
                .find('span');
        }

        $percent.css('width', percentage * 100 + '%');
    });
    // 文件上传成功，给item添加成功class, 用样式标记上传成功。
    uploader.on('uploadSuccess', function (file) {
        $('#' + file.id).addClass('upload-state-done');
    });
    // 文件上传失败，显示上传出错。
    uploader.on('uploadError', function (file) {
        var $li = $('#' + file.id),
            $error = $li.find('div.error');
        // 避免重复创建
        if (!$error.length) {
            $error = $('<div class="error"></div>').appendTo($li);
        }

        $error.text('上传失败');
    });
    // 完成上传完了，成功或者失败，先删除进度条。
    uploader.on('uploadComplete', function (file) {
        $('#' + file.id).find('.progress').remove();
    });

    function random_string(len) {
        len = len || 32;
        var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        var maxPos = chars.length;
        var pwd = '';
        for (i = 0; i < len; i++) {
            pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }

    function get_suffix(filename) {
        pos = filename.lastIndexOf('.')
        suffix = ''
        if (pos != -1) {
            suffix = filename.substring(pos)
        }
        return suffix;
    }

    function calculate_object_name(filename)
    {
        var timestamp = Date.parse(new Date()) / 1000;

        suffix = get_suffix(filename)
        g_object_name = random_string(10) + timestamp + suffix
        return g_object_name;
    }

    /**
     * 保存用户信息Ajax
     * @param name
     * @param role
     */
    function ajaxSave(password, newPassword,img){
        var url = $("#clicksaveRole").val();
        var data = {
            "password" : password,
            "newPassword" : newPassword,
            "img" : img,
        }
        var successFunction = function (res){
            if(res.status==200){
                alert("保存成功");
                window.location.href = "{{url('usermanage/index')}}";
            } else if (res.status == -1) {
                alert("修改失败");
            }
        }

        var errorFunction =function(res){
            alert("修改失败");
        }
        $.ajax({
            url: url,
            data: data,
            type: "post",
            error: errorFunction,
            success: successFunction
        });
    }
    /**
     * 点击保存后的判断
     * @param name
     * @param role
     */
    var clicksaveRole = function(){
        var password = document.getElementById("password").value;
        var newPassword = document.getElementById("newPassword").value;
        var img = document.getElementById('img').value;
        if(password != "" ){
            if(newPassword == "" ){
                $.msgbox("请输入新的密码");
                return false;
            }
        }

        $.msgbox({
            height: 120,
            content: {type: 'confirm', content: '确定要提交吗？'},
            onClose: function (result) {
                if (result) {
                    ajaxSave(password, newPassword,img);
                }
            }
        });

    }


    $(window).load(function () {
        $("#btnsubmit").bind('click',clicksaveRole);
    });

</script>
